import json
import socket
import time

from apscheduler.schedulers.background import BackgroundScheduler

from APN1_2_1.fod.base_fod import get_start_time_from_user
from APN1_2_1.fod.base_car import build_xml


def build_car(msg: list):
    __data = {
        "code": 0,
        "msg": None,
        "data": {
            "bootSuccess": True,
            "bootState": "200",
            "bootStateDesc": None,
            "msg": msg,
        },
    }
    return json.dumps(__data)


def client_server(server="192.168.227.60", port=9003):
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = (server, port)
    client_socket.connect(server_address)

    start_time = get_start_time_from_user()

    car = build_xml()  # 构建车辆台账XML数据
    data = build_car([car])  # 构建车辆台账JSON数据

    def send_msg():
        client_socket.send(data.encode("utf8"))
        print(f"已发送数据")

    send_msg()
    scheduler = BackgroundScheduler()
    scheduler.add_job(send_msg, "interval", seconds=10)
    scheduler.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        scheduler.shutdown()


if __name__ == "__main__":
    client_server()
